//2019240016 大数据191 刘艺 实验一 进程管理
#include <windows.h>
#include <stdio.h>
#include <process.h>

#define BIG_NUMBER 100000000

unsigned  Counter;

//由于在SecondThreadFunc要被引用，所以在前面创建
unsigned  __stdcall ThirdThreadFunc(void* pArguments){
    printf("    --In third thread..\n");

    while (Counter < BIG_NUMBER/2 )
        Counter++;

    printf("    --End of third thread...\n");
    printf("    --Counter should be %ld; it is ->%d\n",BIG_NUMBER,Counter);

    _endthreadex(0);
    return Counter;
    //ThirdThreadFunc创建完毕！！
}


unsigned  __stdcall SecondThreadFunc(void* pArguments){     //创建的第二线程

    printf("--In second thread...Creating third thread...\n");
    HANDLE hTird;   //创建第二子线程
    unsigned threadID;

    hTird = (HANDLE) _beginthreadex( NULL, 0, &ThirdThreadFunc,
                                       NULL, 0, &threadID);

    WaitForSingleObject(hTird,INFINITE);    //死等第二子线程计算完毕

    while (Counter < BIG_NUMBER)  // 第二线程控制累加到五千万
        Counter++;

    printf("--End of second thread...\n");

    _endthreadex(0);
    return 0;
}

int main(){

    HANDLE hThread;
    unsigned threadID;

    printf("In main thread...Creating second thread...\n");


    //创建第二个线程
    hThread = (HANDLE) _beginthreadex( NULL, 0, &SecondThreadFunc,
                                       NULL, 0, &threadID);

    //等待第二个线程终止。如果注释掉下面的行，计数器将不正确，
    // 因为线程尚未终止，并且计数器很可能尚未增加到1000000。

    WaitForSingleObject( hThread, INFINITE );   // INFINITE：死等，等待Counter累加到一亿,注释后该计算没有时间计算
//    WaitForSingleObject( hThread, 3 ); // 调节数值可以得到数值不断着累加，但是无法完成累加一亿的任务
    printf("Counter should be %ld; it is ->%d\n",BIG_NUMBER,Counter);

    //销毁线程对象。。
    CloseHandle( hThread );

    //完成！！！

}
